//
// Created by ChenJi on 2021/7/30.
//
#include "ATController.h"
#include <string.h>
#include <usart.h>
#include <string_library.h>
#include <UartController.h>

char* newLineFlag = "\r\n";
 char* ATPlusFlag = "AT+";

char *cmd;
char *ATStartPtr;
char *ValueStartPtr;
char *EndPtr;
uint8_t CommandLen;
uint8_t value_len;

uint8_t now_at_buffer_index;
extern UART_HandleTypeDef huart2;
uint8_t at_buffer[255];
uint8_t setChannelPocke2t[] = {0xFD,0x02,0x09,26,0xFF};
void HC_ATController_Init() {
    clearATBuffer();
}

void onUart1Message(uint8_t *message, uint16_t size) {
    sendMessageUart3_DMA(message,size);return;
    if (*(message + size - 1) != '\n' || *(message + size - 2) != '\r')
        return;//not end with /r/n
    if((EndPtr=strstr((char*)message, newLineFlag)) == NULL){
        return; //not end ptr;
    }
    if ((ATStartPtr=strstr((char *) message, ATPlusFlag)) == NULL) {
        return; //not AT Command;
    }
    CommandLen = EndPtr - ATStartPtr;
    if((ValueStartPtr=strstr((char *)ATStartPtr, "=")) != NULL){
        ValueStartPtr++;
        value_len = EndPtr - ValueStartPtr;
    }

    cmd = strstr((char *) message, "TestLen?");   //extend your program
    if (cmd != NULL) {

        atAppendString("TestLen=");
        atAppendNumber(CommandLen);
        sendAtBuffer();
        return;
    }
    atAppendString("Error");
    sendAtBuffer();
}

void sendATMessage(char *message) {
    int len = 0;
    for (int i = 0; i <= 255; i++) {
        len++;
        if (*(message + len) == '\0') {
            break;
        }
    }
    HAL_UART_Transmit(&huart1, message, len, 1000);
}
void clearATBuffer(){
    memset(at_buffer,0,now_at_buffer_index);
    now_at_buffer_index=0;
    atAppendString(newLineFlag);
}
void atAppendString(char* str){
    for (int i = 0; i <= 255; i++) {
        if (*(str + i) == '\0') {
            break;
        }
        *(at_buffer+(now_at_buffer_index++))=*(str+i);
    }
}
void atAppendNumber(int num){
    uint8_t nbuf[20];
    myitoa(num, nbuf, 10);
    atAppendString((char *) nbuf);
}
void atAppendHexNumber(int num){
    uint8_t nbuf[20];
    myitoa(num, nbuf, 16);
    atAppendString((char *) nbuf);
}
void sendAtBuffer(){
    atAppendString(newLineFlag);
    HAL_UART_Transmit(&huart1, at_buffer, now_at_buffer_index, 1000);
    clearATBuffer();
}